import type { ObjectDirective } from 'vue'
import { on, off } from './../js/utils/dom'
import { inBrowser } from './../js/utils/is'

const hasTouch = inBrowser && ('ontouchstart' in window)
const initEvent = (ele: HTMLElement, eventBus: (e: Event | TouchEvent) => void): Function => {
  if (hasTouch) {
    const createDocumentHandler = (e: any) => {
      eventBus(e)
      on(ele, 'touchmove', eventBus)
    }
    const removeDocumentHandler = (e: any) => {
      eventBus(e)
      off(ele, 'touchmove', eventBus)
    }

    on(ele, 'touchstart', createDocumentHandler)
    on(ele, 'touchend', removeDocumentHandler)
    on(ele, 'touchcancel', removeDocumentHandler)

    return () => {
      off(ele, 'touchstart', createDocumentHandler)
      off(ele, 'touchend', removeDocumentHandler)
      off(ele, 'touchcancel', removeDocumentHandler)
    }
  } else {
    const createDocumentHandler = (e: any) => {
      eventBus(e)
      on(ele, 'mousemove', eventBus)
    }
    const removeDocumentHandler = (e: any) => {
      eventBus(e)
      off(ele, 'mousemove', eventBus)
    }

    on(ele, 'mousedown', createDocumentHandler)
    on(ele, 'mouseup', removeDocumentHandler)

    return () => {
      off(ele, 'mousedown', createDocumentHandler)
      off(ele, 'mouseup', removeDocumentHandler)
    }
  }
}

let removeFun: Function

const moveEvent: ObjectDirective = {
  beforeMount(el, binding) {
    removeFun = initEvent(el, binding.value)
  },
  unmounted() {
    removeFun()
  }
}

export default moveEvent
